package com.sport.facilities.booking.system;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;


import com.sport.facilities.booking.db.DatabaseHelper;
import com.sport.facilities.booking.system.model.Booking;
import com.sport.facilities.booking.system.model.Friend;
import com.sport.facilities.booking.system.ui.DialogHelper;
import com.sport.facilities.booking.system.ui.FriendListAdapter;
import com.sport.facilities.booking.system.ui.YesAction;

import android.R.string;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.nfc.Tag;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Time;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class FriendListActivity extends Activity implements
		CreateNdefMessageCallback, OnNdefPushCompleteCallback {
	private static final String TAG = "FriendListActivity";

	private FriendListAdapter adapter;
	NfcAdapter mNfcAdapter;
	//TextView sendingText;
	//TextView receivingText;
	private SecureRandom random = new SecureRandom();
	private static final int MESSAGE_SENT = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_list);

		
		/*
		String[] contacts2 = new String[3];

		contacts2[0] = "Ken";
		contacts2[1] = "ken@iceberg.com.hk";
		contacts2[2] = "12341234";
		
        DialogHelper.getOkAlertDialog(this,
				"Received New Contact Info!",
				"Name :" + contacts2[0] + "\n"
			    +"Email :" + contacts2[1] + "\n"
				+"Phone :" + contacts2[2] + "\n"        		
        		).show();
		
		*/
		
		// Check for available NFC Adapter
		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
		if (mNfcAdapter == null) {
			Toast.makeText(this, "NO NFC SUPPORT",
					Toast.LENGTH_LONG).show();

		} else {
			// Register callback to set NDEF message
			mNfcAdapter.setNdefPushMessageCallback(this, this);
			// Register callback to listen for message-sent success
			mNfcAdapter.setOnNdefPushCompleteCallback(this, this);
		}

		final DatabaseHelper db = new DatabaseHelper(this);
		final TextView tvFrdname = (TextView) findViewById(R.id.friend_name_val);
		final TextView tvFrdemail = (TextView) findViewById(R.id.friend_email_val);
		final TextView tvFrdphone = (TextView) findViewById(R.id.friend_phone_val);
		final TextView tvFrdid = (TextView) findViewById(R.id.friend_id_val);
		final ListView lv = (ListView) findViewById(R.id.listView1);

		final Button tvFrddel = (Button) findViewById(R.id.frd_Delete);
		final Button tvFrdupd = (Button) findViewById(R.id.frd_Update);

		final ImageButton imgPhone = (ImageButton) findViewById(R.id.imageButton_Phone);
		final ImageButton imgEmail = (ImageButton) findViewById(R.id.imageButton_Email);

		final Button tvFrdadd = (Button) findViewById(R.id.addnew);

		final FriendListActivity frdlistActivity = this;

		EditText nameEditText = (EditText) findViewById(R.id.friend_name_val);
		nameEditText.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String c = s.toString(); // read Content
				((EditText) findViewById(R.id.friend_name_val_hid)).setText(c); // copy
																				// to
																				// #2

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		EditText emailEditText = (EditText) findViewById(R.id.friend_email_val);
		emailEditText.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String c = s.toString(); // read Content
				((EditText) findViewById(R.id.friend_email_val_hid)).setText(c); // copy
																					// to
																					// #2

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		EditText phoneEditText = (EditText) findViewById(R.id.friend_phone_val);
		phoneEditText.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String c = s.toString(); // read Content
				((EditText) findViewById(R.id.friend_phone_val_hid)).setText(c); // copy
																					// to
																					// #2

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}
		});

		tvFrdadd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (!tvFrdname.getText().toString().equals("")) {

					Friend friend = new Friend();
					friend.setName(tvFrdname.getText().toString());
					friend.setEmail(tvFrdemail.getText().toString());
					friend.setPhone(tvFrdphone.getText().toString());

					long dbNum = db.addFriend(friend);

					if (dbNum > 0) {
						DialogHelper.getOkAlertDialog(frdlistActivity,
								"Add Friend Contact",
								"Add new friend successfully.").show();
						tvFrdid.setText("" + (int) dbNum);
						fnCreatefrdList();
					} else {
						DialogHelper
								.getOkAlertDialog(frdlistActivity,
										"Add Friend Contact",
										"Fail to add new friend.").show();
					}

				}

			}

		});

		imgEmail.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (!tvFrdemail.getText().toString().equals("")) {
					Intent intent = new Intent(Intent.ACTION_SEND);
					intent.setType("plain/text");
					intent.putExtra(Intent.EXTRA_EMAIL,
							new String[] { tvFrdemail.getText().toString() });
					intent.putExtra(Intent.EXTRA_SUBJECT, "subject");
					intent.putExtra(Intent.EXTRA_TEXT, "mail body");
					startActivity(Intent.createChooser(intent, ""));
				}

			}

		});

		imgPhone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (!tvFrdphone.getText().toString().equals("")) {
					Intent callIntent = new Intent(Intent.ACTION_CALL);
					callIntent.setData(Uri.parse("tel:"
							+ tvFrdphone.getText().toString()
									.replaceAll(" ", "")));
					startActivity(callIntent);
				}

			}

		});

		tvFrddel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				
				
				if (!tvFrdid.getText().toString().equals("")) {

					
					boolean tmpChk = false;
					if(!tvFrdname.getText().toString().equals("")){
						tmpChk = true;
					}
					if(!tvFrdphone.getText().toString().equals("")){
						tmpChk = true;
						
					}
					if(!tvFrdemail.getText().toString().equals("")){
						tmpChk = true;						
					}
					
					if(tmpChk){
						

						YesAction yesAction = new YesAction() {
							public void fnDoYesAction() {

								int dbNum = db.deleteFriend(Integer
										.parseInt(tvFrdid.getText().toString()));

								if (dbNum > 0) {
									DialogHelper.getOkAlertDialog(frdlistActivity,
											"Delete a Friend",
											"Delete successfully.").show();

									tvFrdname.setText("");
									tvFrdemail.setText("");
									tvFrdphone.setText("");
									fnCreatefrdList();
								} else {
									DialogHelper.getOkAlertDialog(frdlistActivity,
											"Delete a Friend", "Fail to delete.")
											.show();
								}
							}
						};

						DialogHelper.getYesNoDialog(frdlistActivity,
								"Delete a Friend Contact",
								"Confirm to delete this contact ?", yesAction)
								.show();
						
					}
					

				}

			}

		});

		tvFrdupd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (!tvFrdname.getText().toString().equals("")
						&& !tvFrdid.getText().toString().equals("")) {

					Friend friend = new Friend();
					friend.setName(tvFrdname.getText().toString());
					friend.setEmail(tvFrdemail.getText().toString());
					friend.setPhone(tvFrdphone.getText().toString());
					friend.setId(Integer.parseInt(tvFrdid.getText().toString()));

					int dbNum = db.updateFriend(friend);

					if (dbNum > 0) {
						DialogHelper
								.getOkAlertDialog(frdlistActivity,
										"Update Friend Contact",
										"Update successfully.").show();

						fnCreatefrdList();
					} else {
						DialogHelper.getOkAlertDialog(frdlistActivity,
								"Update Friend Contact", "Fail to update.")
								.show();
					}
				}

			}

		});

		fnCreatefrdList();

	}

	public void fnCreatefrdList() {

		final TextView tvFrdname = (TextView) findViewById(R.id.friend_name_val);
		final TextView tvFrdemail = (TextView) findViewById(R.id.friend_email_val);
		final TextView tvFrdphone = (TextView) findViewById(R.id.friend_phone_val);

		final TextView tvFrdnameHid = (TextView) findViewById(R.id.friend_name_val_hid);
		final TextView tvFrdemailHid = (TextView) findViewById(R.id.friend_email_val_hid);
		final TextView tvFrdphoneHid = (TextView) findViewById(R.id.friend_phone_val_hid);

		final TextView tvFrdid = (TextView) findViewById(R.id.friend_id_val);
		final DatabaseHelper db = new DatabaseHelper(this);
		//final ListView lv = (ListView) findViewById(R.id.listView1);
		
		final ListView lv = (ListView) findViewById(R.id.listView2);

		lv.setBackgroundColor(000000);
		final List<Friend> friendList = db.getAllFriend();

		
		adapter = new FriendListAdapter(this, R.layout.atom_pay_list_item, new ArrayList<Friend>());
		
		
		ListView friendListView = (ListView)findViewById(R.id.listView2);
		friendListView.setAdapter(adapter);

		int count = friendList.size();
		for (int i = 0; i < count; i++) {

			Friend friend = (Friend) friendList.get(i);
			adapter.insert(new Friend(friend.getId(), friend.getName().toString(), friend.getEmail().toString(),  friend.getPhone().toString()), 0);
			
		}
		

		lv.setTextFilterEnabled(true);
		
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				 Object item = parent.getItemAtPosition(position);
				 String myitem = item.toString();
				 //Toast.makeText(getBaseContext(), ""+myitem,
				 //Toast.LENGTH_LONG).show();

				String[] tmpData = myitem.split("!!@@!!##!!");
				 
				tvFrdname.setText(tmpData[0]);
				tvFrdemail.setText(tmpData[1]);
				tvFrdphone.setText(tmpData[2]);
				tvFrdid.setText(tmpData[3]);


				
				
				tvFrdnameHid.setText(tmpData[0]);
				tvFrdemailHid.setText(tmpData[1]);
				tvFrdphoneHid.setText(tmpData[2]);

			}

		});
		
		
		/*
		ArrayAdapter<Friend> adapter = new ArrayAdapter<Friend>(this,
				R.layout.listitem, friendList);

		lv.setAdapter(adapter);

		lv.setTextFilterEnabled(true);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// Toast.makeText(getBaseContext(),
				// friendList.get(position).getPhone(),
				// Toast.LENGTH_LONG).show();

				tvFrdname.setText(friendList.get(position).getName());
				tvFrdemail.setText(friendList.get(position).getEmail());
				tvFrdphone.setText(friendList.get(position).getPhone());
				tvFrdid.setText(Integer.toString(friendList.get(position)
						.getId()));

				tvFrdnameHid.setText(friendList.get(position).getName());
				tvFrdemailHid.setText(friendList.get(position).getEmail());
				tvFrdphoneHid.setText(friendList.get(position).getPhone());

			}

		});
		*/
	}




    /**
     * Implementation for the CreateNdefMessageCallback interface
     */
    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        Time time = new Time();
        time.setToNow();
  
        NdefMessage msg = null;
		final TextView tvFrdnameHid = (TextView) findViewById(R.id.friend_name_val_hid);
		final TextView tvFrdemailHid = (TextView) findViewById(R.id.friend_email_val_hid);
		final TextView tvFrdphoneHid = (TextView) findViewById(R.id.friend_phone_val_hid);

		if (!tvFrdnameHid.getText().toString().equals("") || !tvFrdemailHid.getText().toString().equals("") || !tvFrdphoneHid.getText().toString().equals("")) {

	        String text = (tvFrdnameHid.getText().toString()+"!#!"+tvFrdemailHid.getText().toString()+"!#!"+tvFrdphoneHid.getText().toString());
	        msg = new NdefMessage(NdefRecord.createMime(
	                "application/com.sport.facilities.booking.system", text.getBytes())
	         /**
	          * The Android Application Record (AAR) is commented out. When a device
	          * receives a push with an AAR in it, the application specified in the AAR
	          * is guaranteed to run. The AAR overrides the tag dispatch system.
	          * You can add it back in to guarantee that this
	          * activity starts when receiving a beamed message. For now, this code
	          * uses the tag dispatch system.
	          */
	          //,NdefRecord.createApplicationRecord("com.example.android.beam")
	        );
		}

		
        return msg;
    }

    /**
     * Implementation for the OnNdefPushCompleteCallback interface
     */
    @Override
    public void onNdefPushComplete(NfcEvent arg0) {
        // A handler is needed to send messages to the activity when this
        // callback occurs, because it happens from a binder thread
        mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
    }

    /** This handler receives a message from onNdefPushComplete */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_SENT:
            	

        		final TextView tvFrdname = (TextView) findViewById(R.id.friend_name_val);
        		final TextView tvFrdemail = (TextView) findViewById(R.id.friend_email_val);
        		final TextView tvFrdphone = (TextView) findViewById(R.id.friend_phone_val);
        		final TextView tvFrdid = (TextView) findViewById(R.id.friend_id_val);

        		final TextView tvFrdnameHid = (TextView) findViewById(R.id.friend_name_val_hid);
        		final TextView tvFrdemailHid = (TextView) findViewById(R.id.friend_email_val_hid);
        		final TextView tvFrdphoneHid = (TextView) findViewById(R.id.friend_phone_val_hid);
        		
            	
                Toast.makeText(getApplicationContext(), "Contact Info has been sent!", Toast.LENGTH_LONG).show();
                tvFrdname.setText("");
                tvFrdemail.setText("");
                tvFrdphone.setText("");
                tvFrdid.setText("");
                tvFrdnameHid.setText("");
                tvFrdemailHid.setText("");
                tvFrdphoneHid.setText("");
               
                
                
                break;
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        // Check to see that the Activity started due to an Android Beam
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            processIntent(getIntent());
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        // onResume gets called after this to handle the intent
        setIntent(intent);
    }

    /**
     * Parses the NDEF Message from the intent and prints to the TextView
     */
    void processIntent(Intent intent) {
    	

		final TextView tvFrdname = (TextView) findViewById(R.id.friend_name_val);
		final TextView tvFrdemail = (TextView) findViewById(R.id.friend_email_val);
		final TextView tvFrdphone = (TextView) findViewById(R.id.friend_phone_val);
		final TextView tvFrdid = (TextView) findViewById(R.id.friend_id_val);
    	
        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
                NfcAdapter.EXTRA_NDEF_MESSAGES);
        // only one message sent during the beam
        NdefMessage msg = (NdefMessage) rawMsgs[0];
        // record 0 contains the MIME type, record 1 is the AAR, if present
        
		String splitString = new String(msg.getRecords()[0].getPayload());
		String[] contacts = splitString.split("!#!");
		
		
		

        
        final DatabaseHelper db = new DatabaseHelper(this);
		
		YesAction yesAction = new YesAction() {
			public void fnDoYesAction() {

				if (!tvFrdname.getText().toString().equals("") || !tvFrdemail.getText().toString().equals("") || !tvFrdphone.getText().toString().equals("")) {

					Friend friend = new Friend();
					friend.setName(tvFrdname.getText().toString());
					friend.setEmail(tvFrdemail.getText().toString());
					friend.setPhone(tvFrdphone.getText().toString());

					
					long dbNum = db.addFriend(friend);

			        tvFrdid.setText(""+ dbNum);
					fnCreatefrdList();

				}
	

			}
		};
		
		if(tvFrdname.getText().toString().equals(contacts[0]) && tvFrdemail.getText().toString().equals(contacts[1]) && tvFrdphone.getText().toString().equals(contacts[2])){
			
			
		}
		else{
			// alert box share box
			DialogHelper
					.getOkActionDialog(
							this,
							"Received  New Contact Info!",
							"Name :" + contacts[0] + "\n"
								    +"Email :" + contacts[1] + "\n"
									+"Phone :" + contacts[2] + "\n",
							yesAction)
					.show();
	        
		}

        tvFrdname.setText(contacts[0]);
        tvFrdemail.setText(contacts[1]);
        tvFrdphone.setText(contacts[2]);
        
        /*
        DialogHelper.getOkAlertDialog(this,
				"Received New Contact Info!",
				"Name :" + contacts[0] + "\n"
			    +"Email :" + contacts[1] + "\n"
				+"Phone :" + contacts[2] + "\n"        		
        		).show();
        */
        
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // If NFC is not available, we won't be needing this menu
        if (mNfcAdapter == null) {
            return super.onCreateOptionsMenu(menu);
        }
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        case R.id.menu_save:
        	savePreferentes(getApplicationContext());

            return true;
        
 
        case R.id.menu_load:

        	loadPreferences(getApplicationContext());

            return true;
        
            case R.id.menu_settings:
                Intent intent = new Intent(Settings.ACTION_NFCSHARING_SETTINGS);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    


    /* ... */

    private void savePreferentes(Context context) {
    	

    	TextView tvFrdname2 = (TextView) findViewById(R.id.friend_name_val);
    	TextView tvFrdemail2 = (TextView) findViewById(R.id.friend_email_val);
    	TextView tvFrdphone2 = (TextView) findViewById(R.id.friend_phone_val);

    	if (!tvFrdname2.getText().toString().equals("") && !tvFrdemail2.getText().toString().equals("") &&  !tvFrdphone2.getText().toString().equals("")) {
    		

            String PREFS_NAME = "preferences";
            String PREF_CONTACTNAME = "pref_contactname";
            String PREF_CONTACTEMAIL = "pref_contactemail";
            String PREF_CONTACTPHONE = "pref_contactphone";
            /* ... */

             final String yourDefaultUsernameValue = "None";
             String contactNameValue = tvFrdname2.getText().toString();
             String contactEmailValue = tvFrdemail2.getText().toString();
             String contactPhoneValue = tvFrdphone2.getText().toString();

        	
          SharedPreferences settings = 
            getSharedPreferences(PREFS_NAME, Context.MODE_APPEND);
          SharedPreferences.Editor editor = settings.edit();

          // Edit and commit
          editor.putString(PREF_CONTACTNAME, contactNameValue);
          editor.putString(PREF_CONTACTEMAIL, contactEmailValue);
          editor.putString(PREF_CONTACTPHONE, contactPhoneValue);
          editor.commit();
          
          Toast.makeText(getApplicationContext(), "NFC exchange contact info have been saved!", Toast.LENGTH_LONG).show();
    	}
    	
    }

    private void loadPreferences(Context context) {
    	

    	TextView tvFrdname2 = (TextView) findViewById(R.id.friend_name_val);
    	TextView tvFrdemail2 = (TextView) findViewById(R.id.friend_email_val);
    	TextView tvFrdphone2 = (TextView) findViewById(R.id.friend_phone_val);

    	
        String PREFS_NAME = "preferences";
        String PREF_CONTACTNAME = "pref_contactname";
        String PREF_CONTACTEMAIL = "pref_contactemail";
        String PREF_CONTACTPHONE = "pref_contactphone";
        /* ... */

         final String yourDefaultUsernameValue = "None";

    	
      SharedPreferences settings = 
        getSharedPreferences(PREFS_NAME, Context.MODE_APPEND);

      // Get value
      tvFrdname2.setText(settings.getString(
    		  PREF_CONTACTNAME, 
        yourDefaultUsernameValue));
      tvFrdemail2.setText(settings.getString(
    		  PREF_CONTACTEMAIL, 
        yourDefaultUsernameValue));
      tvFrdphone2.setText(settings.getString(
    		  PREF_CONTACTPHONE, 
        yourDefaultUsernameValue));
      
      

      Toast.makeText(getApplicationContext(), "NFC exchange contact info have been loaded!", Toast.LENGTH_LONG).show();
      
    }
	
	
	
	
	

}
